package za.org.jcicada.genss.sensor.impl;

import java.util.Observable;

import za.org.jcicada.genss.sensor.ISensorValue;
import za.org.jcicada.genss.sensor.SensorURN;

public abstract class StrategyDifferential extends StrategyBase {

	private static final long serialVersionUID = 1L;
	private double lastValue;
    protected double threshold;
    
    /**
     * Construct event strategy and initialise status and value so that on update
     * it will immediately notify.
     * @param sensorURN the sensor URI
     * @param threshold difference threshold to be exceeded before notify
     */
    public StrategyDifferential(SensorURN sensorURN, double threshold) {
        super(sensorURN);
        lastValue = 0;
        this.threshold = threshold;
    }
    
    /**
     * Implement this in a derived class.
     * @return the value of the sensor as a double
     */
    protected abstract double getValueAsDouble(ISensorValue value);
    
    /**
     * If either the status or value has changed then notify.
     * @param o the sensor that is being observed
     * @param arg ignored
     */
    @Override
    protected void updateValue(Observable o, ISensorValue value) {
        double currentValue = getValueAsDouble(value);
        if (Math.abs(currentValue - lastValue) > threshold) {
            lastValue = currentValue;
            notifySample(value);
        }
    }

}
